//
//  ZhiFuViewController.m
//  1243
//
//  Created by 我的 on 16/4/20.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "ZhiFuViewController.h"
#import "OrderPayTableViewCell.h"
#import "PayOrderTwoTableViewCell.h"
#import "SVProgressHUD.h"
#import "NetWorkTools.h"

#import "ShopCartViewController.h"
#import "JudgeUserLogInTool.h"
#import "LoginViewController.h"

#import "RKAlertView.h"

@interface ZhiFuViewController ()
<
    UIAlertViewDelegate
>
{
    NSMutableArray *boolArray;
    //交易密码
    NSString *payPassword;
}

@property (nonatomic,copy)NSString *payType;

@property (nonatomic, copy) NSString *message;

@property (nonatomic,strong) NSDictionary *loadUserData;

@property (nonatomic,copy)NSString *gouwuQuanCount;

@property(nonatomic,strong)NSArray *GoArray;

@end

@implementation ZhiFuViewController

- (NSString *)payType {
    if (!_payType) {
        
        if ([self.str isEqualToString:@"积分专区"]) {
            _payType = @"3";
        }else {
            _payType = @"0";
        }
        
        
    }
    return _payType;
}

- (NSDictionary *)loadUserData {
    if (!_loadUserData) {
        _loadUserData = [NSDictionary dictionary];
    }
    return _loadUserData;
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    boolArray = [NSMutableArray arrayWithObjects:@"1",@"0", @"0", nil];
    
    self.title = @"支付订单";
    
    [self.tableView registerNib:[UINib nibWithNibName:@"OrderPayTableViewCell" bundle:nil] forCellReuseIdentifier:@"OrderPayTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"PayOrderTwoTableViewCell" bundle:nil] forCellReuseIdentifier:@"PayOrderTwoTableViewCell"];
    
    [self loadData];
    
    [self gouWuQuanCount];
    [self getShoesAndColorData];
    [self shopCarButton];
}

/**
 *  购物车按钮
 */

- (void)shopCarButton
{
    UIButton *shopCart = [[UIButton alloc] init];
    
    [shopCart addTarget:self action:@selector(clickShopCart) forControlEvents:UIControlEventTouchUpInside];
    [shopCart setImage:[UIImage imageNamed:@"gouwuche"] forState:UIControlStateNormal];
    [shopCart setFrame:CGRectMake(WIDTH - 60, HEIGHT - 170+64, 30, 30)];
    [shopCart setImage:[UIImage imageNamed:@"gouwuche"] forState:UIControlStateNormal];
    [self.view addSubview:shopCart];
}

- (void)clickShopCart {
    NSLog(@"...");
    if ([JudgeUserLogInTool JudgeUserLonInStatus]) {
        
        [self.navigationController pushViewController:[[ShopCartViewController alloc] init] animated:YES];
    }else{
        LoginViewController *a = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:[NSBundle mainBundle]];
        [self presentViewController:a animated:YES completion:nil];
        
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
#warning change;
        NSString *str   =[self.str substringToIndex:2];
        
        if ([self.str isEqualToString:@"积分赠送专区"]||[self.str isEqualToString:@"积分专区"] ||[self.str isEqualToString:@"兑换"]) {
            return 1;
        }
        return 2;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        OrderPayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderPayTableViewCell" forIndexPath:indexPath];
//        NSString *str   =[self.str substringToIndex:2];
//        NSString *temp = [self.str substringFromIndex:2];
//        
//        int number = [temp intValue];
//        
        if ([self.str isEqualToString:@"兑换"]) {
            
            if ([self.BuyQuan isEqualToString:@"购物券"]) {
                
                cell.OrderPayPriceLabel.text = [NSString stringWithFormat:@"%.f张",self.allPrice];
                
            }else{
                
                int user = [[self.GoArray[indexPath.row] objectForKey:@"NeedCardNum"] intValue] *[self.number intValue];
                cell.OrderPayPriceLabel.text = [NSString stringWithFormat:@"%d张",user];
                
            }
  
        }else {
            cell.OrderPayPriceLabel.text = [NSString stringWithFormat:@"%0.1f", self.allPrice];
        }
        return cell;
    } else {
        
        PayOrderTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PayOrderTwoTableViewCell" forIndexPath:indexPath];
        
        cell.paySelectView.layer.borderWidth = 2;
        cell.paySelectView.layer.cornerRadius = CGRectGetHeight(cell.paySelectView.frame)/2;
        cell.paySelectView.layer.masksToBounds = YES;
        
      
        if ([self.str isEqualToString:@"积分赠送专区"]) {
            cell.PayTwoTitleLabel.text = [NSString stringWithFormat:@"账户余额 : %.2f",[[self.loadUserData objectForKey:@"Money"] floatValue]];;
        }if ([self.str isEqualToString:@"积分专区"]) {
             cell.PayTwoTitleLabel.text = [NSString stringWithFormat:@"可用积分 : %.2f",[[self.loadUserData objectForKey:@"gq_Money"] floatValue]];
        }else if ([self.str isEqualToString:@"兑换"]){
            // 购物券
             cell.PayTwoTitleLabel.text = [NSString stringWithFormat:@"当前购物券 : %@",self.gouwuQuanCount];
            
        }else{
            if (indexPath.row == 0) {
                cell.PayTwoTitleLabel.text = [NSString stringWithFormat:@"账户余额 : %.2f",[[self.loadUserData objectForKey:@"Money"] floatValue]];;
            } else {
                cell.PayTwoTitleLabel.text = [NSString stringWithFormat:@"可用积分 : %.2f",[[self.loadUserData objectForKey:@"gq_Money"] floatValue]];
            }
            
            
        }
        
        
        
        if ([boolArray[indexPath.row] isEqualToString:@"1"]) {
            cell.paySelectView.backgroundColor = [UIColor greenColor];
        } else {
            cell.paySelectView.backgroundColor = [UIColor whiteColor];
        }
        
        return cell;
    }
}

#pragma mark - UITableView Delegate 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 1) {
        
        for (NSInteger i=0; i<boolArray.count; i++) {
            if (indexPath.row == i) {
                boolArray[i] = @"1";
            }else{
                boolArray[i] = @"0";
            }
        }
        
        if (indexPath.row == 0) {
            self.payType = @"0";
        } else {
            self.payType = @"3";
        }
    }
    
    NSLog(@"%@",self.payType);
    
    [self.tableView reloadData];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    if (section ==  1) {
        return @"支付方式";
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 0.01;
    } else {
        return 60;
    }
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 1) {
        UIView *footView = [[UIView alloc] init];
        UIButton *GoPayMentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        GoPayMentBtn.frame = CGRectMake(30, 10, WEITH-60, 40);
        GoPayMentBtn.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
        [GoPayMentBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        GoPayMentBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        GoPayMentBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [GoPayMentBtn setTitle:@"立即支付" forState:UIControlStateNormal];
        [GoPayMentBtn addTarget:self action:@selector(GoPayMentBtnClick) forControlEvents:UIControlEventTouchUpInside];
        GoPayMentBtn.layer.cornerRadius = 6;
        GoPayMentBtn.layer.masksToBounds = YES;
        [footView addSubview:GoPayMentBtn];
        return footView;
    }
    return nil;
}

- (void)GoPayMentBtnClick {
    
//    [SVProgressHUD show];
//    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        
//        [SVProgressHUD dismiss];
//        
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"支付失败" message:@"账户余额不足" preferredStyle:UIAlertControllerStyleAlert];
//        
//        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            
//        }];
//        
//        [alert addAction:action];
//        
//        [self presentViewController:alert animated:YES completion:nil];
//    });

    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStyleSecureTextInput;
    UITextField *payText = [alert textFieldAtIndex:0];
    payText.placeholder = @"请输入您的支付密码";
    alert.tag = 521;
    [alert show];
    

    
}


/**
 *  删除购物车订单
 */
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 11111) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    if (buttonIndex == 1 && alertView.tag == 521) {
       payPassword = [alertView textFieldAtIndex:0].text;
        if ([payPassword isEqualToString:self.loadUserData[@"Buy_Password"]]) {
            //判断普通商城 购物券  积分 支付方式
            if ([self.str isEqualToString:@"兑换"]) {
                [self payMoneyData:@"6"];
            }else {
                [self payMoneyData:self.payType];
            }
        }else {
            
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您输入的交易密码有误" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}

- (void)payMoneyData:(NSString *)str
{
    NSDictionary *dict = [ReadLoginData readLoginData];
    
    NSString *userId = [dict objectForKey:@"Number"];
    
    NSDictionary *params = @{
                             @"UserId":userId,
                             @"UserName":[dict objectForKey:@"UserName"],
                             @"OrderNumber":self.orderArray[0],
                             @"PayMoneyType":str
                             };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"PAYORDERMUT" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        self.message = [object objectForKey:@"Message"];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:self.message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 11111;
        [alert show];
        
        NSMutableArray *array = [NSMutableArray array];
        NSMutableArray *array1 = [NSMutableArray array];
        [array addObjectsFromArray:[ReadLoginData readShopArr]];
        
        if (self.num == 1) {
            for (int i = 0; i < array.count; i ++) {
                [array1 addObject:array[i]];
                for (int j = 0; j < array1.count; j ++) {
                    if ([array[i][j][@"isPay"] integerValue] == 1) {
                        if (array1.count ==1) {
                            [array removeObjectAtIndex:i];
                        } else {
                            [array[i] removeObjectAtIndex:j];
                        }
                    }
                }
                [ReadLoginData saveShopDataToLocal:array];
            }
        }
    }];
    
    

    
    

}




- (void)loadData
{
    NSDictionary *dict = @{
                           @"PhoneNum":[ReadLoginData readLoginData][@"UserName"],
                           @"Password":[ReadLoginData readLoginData][@"Password"]
                           };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"USERLOGIN" completeBlock:^(id object) {
        
        NSDictionary *loginDict = [NetWorkTools dictionaryWithJsonString:[object objectForKey:@"BackData"]];

        [ReadLoginData savelogindataToLocal:loginDict];
        
        self.loadUserData = [ReadLoginData readLoginData];
        
        [self.tableView reloadData];

    }];
}

//购物券数量请求
- (void)gouWuQuanCount
{
    NSDictionary *dict = [ReadLoginData readLoginData];
    
    if (dict.count) {
        
        NSString *userId = [dict objectForKey:@"Number"];
        
        NSDictionary *params = @{
                                 @"UserNumber":userId
                                 };
        
        [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params     AndMenthodName:@"BUYCARDCOUNT" completeBlock:^(id object) {
            
            self.gouwuQuanCount = [object objectForKey:@"BackData"];

            [self.tableView reloadData];
        }];
    }
}
///获取给分类下的所有商品
- (void)getShoesAndColorData{
    //NeedCardNum
    NSDictionary *dict = @{
                           @"SortName":@"",
                           @"PageIndex":@"1",
                           @"PageSize":@"10",
                           @"Postion":@"2",
                           //                           @"Sign":@"9568F4B2ED27BD2E3BE1A1C488669658A508B626"
                           };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"PRODUCTLISTQUERY" completeBlock:^(id object) {
        
        NSString *DataString = [object objectForKey:@"BackData"];
        
        NSDictionary *dict = [NetWorkTools dictionaryWithJsonString:DataString];
        
        
        self.GoArray = [dict objectForKey:@"ds"];
        NSLog(@"%@",self.GoArray);
        [self.tableView reloadData];
        
    }];
    
}


@end
